import { assign } from 'lodash';
import { AnyAction } from 'redux';
import ACTIONS from 'constants/attachment';
import { arrayRemoveItem } from 'utils/utils';

const initialState: Record<string, any> = {
  attachTotal: 0,
  attachList: [],
  selectedItems: [],
};
let selectedItems = [];

export default (state = initialState, action: AnyAction) => {
  switch (action.type) {
    case ACTIONS.FETCH_ATTACHMENT_LIST_SUCCESS:
      return assign({}, state, {
        attachList: action.response.data.items,
        attachTotal: action.response.data.total,
      });

    case ACTIONS.TOGGLE_ITEM_CHECK:
      selectedItems = state.selectedItems;
      if (action.checked) {
        if (action.max === 0 || selectedItems.length < action.max) {
          selectedItems = [action.item, ...selectedItems];
        }
      } else {
        selectedItems = arrayRemoveItem(selectedItems, action.item);
      }

      return assign({}, state, {
        selectedItems: selectedItems.slice(),
      });

    case ACTIONS.INIT_SELECTED_ITEM:
      return assign({}, state, {
        selectedItems: action.ownItems,
      });

    default:
      return state;
  }
};
